import { defineStore, acceptHMRUpdate } from 'pinia'
import instance, { request } from '@/service/request'
import Storage from '@/utils/Storage'
import { TOKEN_KEY } from '@/config/constant'

export interface UserDataProps {
  username?: string
  id?: string
  phoneNumber?: string
  nickName?: string
  description?: string
  updatedAt?: string
  createdAt?: string
  iat?: number
  exp?: number
  picture?: string
  gender?: string
}

export interface UserProps {
  isLogin: boolean
  token?: string
  data: UserDataProps
}

export const useUserStore = defineStore('user', {
  state: (): UserProps => ({
    isLogin: false,
    data: {},
    token: Storage.getStorage(TOKEN_KEY)
  }),

  actions: {
    async loginAndFetch(payload: any) {
      await this.login(payload)
      return await this.fetchCurrentUser()
    },

    async login(payload: any) {
      const rawData = await request<{ token: string }>('/users/loginByPhoneNumber', 'post', payload, 'login')
      this.token = rawData.data.token
      Storage.setStorage(TOKEN_KEY, this.token)
      instance.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
    },

    async fetchCurrentUser() {
      const rawData = await request<UserDataProps>('/users/getUserInfo', 'get')
      this.updateUser(rawData.data)
      return rawData.data
    },

    updateUser(data: UserDataProps) {
      this.isLogin = true
      this.data = { ...data }
    },

    logout() {
      this.token = ''
      this.isLogin = false
      Storage.remove(TOKEN_KEY)
      delete axios.defaults.headers.common['Authorization']
    }
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}
